<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>{{html_title}}</title>
    <script src=" http://maps.google.com/?file=api&amp;v=2.x&amp;key=ABQIAAAAQTvsJ2owxKVgw4mWUf5J9RSuuSmsr1s_zcKGw-y6vBLMf-vwuBT3g-FWpuAH5JbauXKHxHdpH1fRkw"
      type="text/javascript"></script>
    <script src="/js/domloaded.js" type="text/javascript"></script>
    <style type="text/css">
      body {
        font-family: Verdana, Arial, sans serif;
        font-size: 11px;
        margin: 2px;
      }
      table.directions th {
	background-color:#EEEEEE;
      }
	  
      img {
        color: #000000;
      }
    </style>
    <script type="text/javascript" src="http://json.org/json2.js"></script>

    <script type="text/javascript">
    var JSONwandering;
    //
    // As mentioned at http://en.wikipedia.org/wiki/XMLHttpRequest
    //
    if( !window.XMLHttpRequest ) XMLHttpRequest = function()
    {
      try{ return new ActiveXObject("Msxml2.XMLHTTP.6.0") }catch(e){}
      try{ return new ActiveXObject("Msxml2.XMLHTTP.3.0") }catch(e){}
      try{ return new ActiveXObject("Msxml2.XMLHTTP") }catch(e){}
      try{ return new ActiveXObject("Microsoft.XMLHTTP") }catch(e){}
      throw new Error("Could not find an XMLHttpRequest alternative.")
    };

    //
    // Makes an AJAX request to a local server function w/ optional arguments
    //
    // functionName: the name of the server's AJAX function to call
    // opt_argv: an Array of arguments for the AJAX function
    //
    function Request(function_name, opt_argv) {

      if (!opt_argv)
        opt_argv = new Array();

      // Find if the last arg is a callback function; save it
      var callback = null;
      var len = opt_argv.length;
      if (len > 0 && typeof opt_argv[len-1] == 'function') {
        callback = opt_argv[len-1];
        opt_argv.length--;
      }
      var async = (callback != null);

      // Encode the arguments in to a URI
      var query = 'action=' + encodeURIComponent(function_name);
      for (var i = 0; i < opt_argv.length; i++) {
        var key = 'arg' + i;
        var val = JSON.stringify(opt_argv[i]);
        query += '&' + key + '=' + encodeURIComponent(val);
      }
      query += '&time=' + new Date().getTime(); // IE cache workaround

      // Create an XMLHttpRequest 'GET' request w/ an optional callback handler
      var req = new XMLHttpRequest();
      req.open('GET', '/rpc?' + query, async);

      if (async) {
        req.onreadystatechange = function() {
          if(req.readyState == 4 && req.status == 200) {
            var response = null;
            try {
                //alert(responseText);
             response = JSON.parse(req.responseText);
            } catch (e) {
             response = req.responseText;
            }
            callback(response);
          }
        }
      }

      // Make the actual request
      req.send(null);
    }

    // Adds a stub function that will pass the arguments to the AJAX call
    function InstallFunction(obj, functionName) {
    //alert('install function');
      obj[functionName] = function() { Request(functionName, arguments); }
    }

    </script>
    <script type="text/javascript">

    function getQuerystring(key, default_)
    {
      if (default_==null) default_="";
      key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
      var qs = regex.exec(window.location.href);
      if(qs == null)
        return default_;
      else
        return qs[1];
    }
    // Server object that will contain the callable methods
    var server = {};

    // Insert 'Add' as the name of a callable method
    InstallFunction(server, 'Add');

    // Insert 'GetWanderings' as the name of a callable method
    InstallFunction(server, 'GetWanderings');

    // Insert 'GetWanderings' as the name of a callable method
    InstallFunction(server, 'GetDroids');
    
    // Handy "macro"
    function $(id){
      return document.getElementById(id);
    }

    // Client function that calls a server rpc and provides a callback
    function getWanderings() {
        var twitteruser = '';
        twitteruser = getQuerystring('tuser');
        maphead = document.getElementById('mapheading');
        
        maphead.innerHTML = twitteruser + " went walking.";
        document.getElementById('followme').innerHTML = 'Follow me on <a href="http://twitter.com/' + twitteruser + '">twitter</a>';
        server.GetWanderings(twitteruser, onAddSuccess);
    }

    function getDroids() {
        var twitteruser = '';
        //twitteruser = getQuerystring('tuser');
        //maphead = document.getElementById('mapheading');
        
        //maphead.innerHTML = twitteruser + " went walking.";
        //document.getElementById('followme').innerHTML = 'Follow me on <a href="http://twitter.com/' + twitteruser + '">twitter</a>';
        server.GetDroids(onAddSuccess);
    }

    // Callback for after a successful doAdd
    function onAddSuccess(response) {
      //$('result').value = response;
      //alert(JSONwandering);
      
      //alert(JSONwandering);
      
      
        var objDroids = eval('(' + response + ')');
        //alert(objDroids.length);
        var points = new Array();
        var pcount = 0;
        /*for (var i=objDroids.length-1; i>=0; --i)
        {  //alert(objWanderings[i]['lat']);
            
            points[pcount][0] = objDroids[i]['lat'];
            points[pcount][1] = objDroids[i]['lng'];
            pcount++
            }*/
        /*alert(points);*/
        setDroids(objDroids);
        
      
    }

    </script>   
    
    <script type="text/javascript">
 
    var map;
    var gdir;
    var geocoder = null;
    var addressMarker;

    function initialize() {
      //alert('hello');
      /*if (GBrowserIsCompatible()) {      
        var icon = new GIcon();
        icon.image = "http://www.google.com/mapfiles/turkey.png";
        icon.shadow = "http://www.google.com/mapfiles/turkeyshadow.png";
        icon.iconSize = new GSize(59, 62);
        icon.shadowSize = new GSize(91, 62);
        icon.iconAnchor = new GPoint(37, 59);
        icon.infoWindowAnchor = new GPoint(31, 8);

        
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        
        //alert('I have loaded the map');
        // map.setCenter(new GLatLng(51.501637,-0.126257), 12);
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        //get wandering data from datastore
        alert('getting the map points');

      }
        */
        
        var jsonTest = getDroids();
      
      //gdir.loadFromWaypoints(points);
 

    }
    
    function setDirections(waypoints) {
      gdir.loadFromWaypoints(waypoints, {travelMode:G_TRAVEL_MODE_WALKING});
    }

    
    function setDroids(locations) {
        if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map_canvas"));
            map.setMapType(G_HYBRID_MAP);
            map.setCenter(new GLatLng(47.583172,-122.154806), 15);
            map.setUIToDefault();
            
            var myIcon = new GIcon(G_DEFAULT_ICON);
            myIcon.image = "/images/droid_no_shadow.png";
            myIcon.iconSize = new GSize(22, 31);
            myIcon.shadow = "/images/droidshadow.png";
            myIcon.shadowSize = new GSize(42, 31);
            myIcon.iconAnchor = new GPoint(10, 29);
            myIcon.infoWindowAnchor = new GPoint(10, 14);
            //myIcon.printImage = "/images/my_custom_icon_print.gif";
            //myIcon.mozPrintImage = "/images/my_custom_icon_mozPrint.gif";
            //myIcon.printShadow = "/images/my_custom_icon_printShadow.gif";
            //myIcon.transparent = "/images/my_custom_icon_transparent.png";
            myIcon.imageMap = [ 10,29, 1,16, 0,5, 5,0, 12,4, 18,2, 21,12, 21,16 ]; 
            
            
            var blueIcon = new GIcon(G_DEFAULT_ICON);
            blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
    		
    		// Set up our GMarkerOptions object
            
    		markerOptions = { icon:myIcon };

            // Add 10 markers to the map at random locations
            var bounds = map.getBounds();
            var southWest = bounds.getSouthWest();
            var northEast = bounds.getNorthEast();
            var lngSpan = northEast.lng() - southWest.lng();
            var latSpan = northEast.lat() - southWest.lat();

            for (var i = 0; i < locations.length; i++) {
              var latlng = new GLatLng(locations[i]['lat'] + (latSpan / 2) * Math.random(), locations[i]['lng']);
              map.addOverlay(createMarker(latlng, markerOptions, locations[i]['user']));
            }
        }
    }
    
    function createMarker(point, markerOpts, text) {
      // Create a lettered icon for this point using our icon class
      
      // Set up our GMarkerOptions object
      //markerOptions = { icon:droidIcon };
      var marker = new GMarker(point, markerOpts);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml("I am <b>" + text + "</b> follow me <a href ='http://twitter.com/" + text + "'>here</a>");
      });
      return marker;
    }
    
    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
    
    //alert('load dom');
    DomLoaded.load(initialize);

    
    </script>

  </head>
  <body onload="" onunload="GUnload()">
  
  <!--h2 id="mapheading"></h2> <p id="followme">Follow me on <a href="http://twitter.com/kidbeats">twitter</a></p-->
  <form action="#" onsubmit="setDirections(this.from.value, this.to.value, this.locale.value); return false">

</form>

    <br/>
    <table class="directions">
    <!--tr><th>Formatted Directions</th><th>Map</th></tr-->

    <tr>
    <!--td valign="top"><div id="directions" style="width: 275px"></div></td-->
    <td valign="top"><div id="map_canvas" style="width:540px; height: 540px"></div></td>

    </tr>
    </table> 
  </body>
</html>
